import { createApp } from 'vue'
import { createPinia } from 'pinia'
import type { SysPermission } from './api/sysPermission/sysPermission.d'

import App from './App.vue'
import router, { addRouter } from './router'

//引入ArocVue
import ArcoVue from '@arco-design/web-vue'
import '@arco-design/web-vue/dist/arco.min.css'
import ArcoVueIcon from '@arco-design/web-vue/es/icon'

//引入bootstrap
import 'bootstrap/dist/css/bootstrap.min.css'

//引入持久化
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import { useGlobalStore } from '@/stores/global'
import type { SysMenu } from '@/api/sysMenu/sysMenu.d'

const app = createApp(App)

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(pinia)

{
//重新加载路由
  const globalStore = useGlobalStore()
  globalStore.menus?.forEach((value: SysMenu) => {
    addRouter(value)
  })
  const permissionMap = new Map()
  //@ts-ignore
  globalStore.permissions?.forEach((value: SysPermission) => {
    permissionMap.set(value.name, 1)
  })

  app.directive('permission', {
    //挂载哉时
    mounted(el: HTMLElement, binding) {
      if (!permissionMap.has(binding.value)) {
        //如果不存在这个权限就移除
        el.parentNode && el.parentNode.removeChild(el)
      }
    },
    updated(el, binding) {
      if (!permissionMap.has(binding.value) && el.parentNode) {
        el.parentNode.removeChild(el)
      }
    }
  })
}

app.use(router)
app.use(ArcoVue)
app.use(ArcoVueIcon)

app.mount('#app')
